//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by celeste on 16/5/17.
//  Copyright © 2016年 celeste. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 身份验证控制器
class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "取消",
            style: .Plain,
            target: self,
            action: "clickCloseButton")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "自动填充",
            style: .Plain,
            target: self,
            action: "clickAutoFillButton")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //纯代码开发中,所有的view都要指定背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        //加载授权 URL
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
        webView.delegate = self
        
    }
    
    
    //监听方法
    @objc private func clickCloseButton() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func clickAutoFillButton() {
        
        let js = "document.getElementById('userId').value='18267911977';" + "document.getElementById('passwd').value='13722262888';"
        //执行js
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
}
extension OAuthViewController: UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let urlString = request.URL?.absoluteString
            where !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri){
                
                return true
        }
        guard let query = request.URL?.query where query.hasPrefix("code=") else {
            
            dismissViewControllerAnimated(true, completion: nil)
            return false
        }
        // 获得请求码
        let code = query.substringFromIndex("code=".endIndex)
        //发起网络请求
        NetworkTools.sharedTools.loadAccessToken(code) { (result) -> () in
            
            guard let result = result else {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            // 设置用户账户单例的数据
            UserAccount.sharedUserAccount.updateUserAccount(result)
            
            // 登录成功
            // 1> 通知代理工作
            NSNotificationCenter.defaultCenter().postNotificationName(LDWeiBoLoginSuccessedNotification, object: nil)
            
            SVProgressHUD.showInfoWithStatus("登录成功")
            
            delay() {
                // 2> 关闭视图控制器
                self.clickCloseButton()
            }
        }
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}

